<template>
  <div class="player" v-show="playList.length > 0 ">
    <transition name="normal" @enter="enter" @after-enter="afterEnter" @leave="leave" @after-leave="afterLeave">
      <div class="normal-player" v-show="fullScreen">
        <div class="background">
          <img width="100%" height="100%" :src="currentSong.img">
        </div>
        <div class="top">
          <div class="back" @click="back">
            <i class="icon-back"></i>
          </div>
          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="subtitle" v-html="currentSong.singer"></h2>
        </div>
        <!-- <div class="middle">
          <div class="middle-l">
            <div class="cd-wrapper" ref="cdWrapper">
              <div class="cd" :class="cdcls">
                <img class="image" :src="currentSong.img">
              </div>
            </div>
          </div>
          <scroll class="middle-r" ref="lyricList" :data="currentLyric && currentLyric.lines">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p ref="lyricLine" class="text" :class="{'current':currentLineNum == index}" v-for="(line,index) in currentLyric.lines" :key="index">{{line.txt}}</p>
              </div>
            </div>
          </scroll>
        </div> -->
        <swiper class="middle" :options="swiperOption">
          <!-- slides -->
          <swiper-slide>
            <div class="middle-l">
              <div class="cd-wrapper" ref="cdWrapper">
                <div class="cd" :class="cdcls">
                  <img class="image" :src="currentSong.img">
                </div>
              </div>
              <div class="playing-lyric-wrapper">
                <div class="playing-lyric">{{playingLyric}}</div>
              </div>
            </div>
          </swiper-slide>
          <swiper-slide>
            <scroll class="middle-r" ref="lyricList" :data="currentLyric && currentLyric.lines">
              <div class="lyric-wrapper">
                <div v-if="currentLyric">
                  <p ref="lyricLine" class="text" :class="{'current':currentLineNum == index}" v-for="(line,index) in currentLyric.lines" :key="index">{{line.txt}}</p>
                </div>
              </div>
            </scroll>
          </swiper-slide>

        </swiper>
        <div class="bottom">
          <!-- Optional controls -->
          <div class="swiper-pagination" slot="pagination"></div>
          <div class="progress-wrapper">
            <span class="time time-l">{{format(currentTime)}}</span>
            <div class="progress-bar-wrapper">
              <progress-bar :percent="percent" @percentChane="onProgressBarChange"></progress-bar>
            </div>
            <span class="time time-r">{{format(currentSong.duration)}}</span>
          </div>
          <div class="operators">
            <div class="icon i-left" @click="changeMode">
              <i :class="iconMode"></i>
            </div>
            <div class="icon i-left" :class="disableCls">
              <i class="icon-prev" @click="prev"></i>
            </div>
            <div class="icon i-center" :class="disableCls">
              <i :class="playIcon" @click="togglePlaying"></i>
            </div>
            <div class="icon i-right" :class="disableCls">
              <i class="icon-next" @click="next"></i>
            </div>
            <div class="icon i-right">
              <i :class="classFavorite(currentSong)" @click.stop="clickFavorite(currentSong)"></i>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click="open">
        <div class="icon">
          <img :class="cdcls" width="40" height="40" :src="currentSong.img">
        </div>
        <div class="text">
          <h2 class="name" v-html="currentSong.name"></h2>
          <p class="desc" v-html="currentSong.singer"></p>
        </div>
        <div class="control">
          <progress-circle :radius="radius" :percent="percent">
            <i class="icon-mini" :class="miniIcon" @click.stop="togglePlaying"></i>
          </progress-circle>
        </div>
        <div class="control" @click.stop="iconShowList">
          <i class="icon-playlist"></i>
        </div>
      </div>
    </transition>
    <play-list ref="playListRef"></play-list>
    <audio ref="audio" :src="songUrl" @play="ready" @error="error" @timeupdate="updateTime" @ended="end"></audio>
  </div>
</template>

<script>
  import {
    mapGetters,
    mapMutations,
    mapActions
  } from "vuex";
  import animations from "create-keyframe-animation";
  import progressBar from 'base/progress-bar/progressBar';
  import progressCircle from 'base/progress-circle/progressCircle';
  import {
    playMode
  } from 'common/js/config';
  import Lyric from 'lyric-parser';
  import Scroll from 'base/scroll/scroll';
  import PlayList from 'components/playList';
  import {
    getSingerUrl
  } from 'api/singer';
  import {
    playerMixin
  } from 'common/js/mixin';

  export default {
    name: "Player",
    mixins: [playerMixin],
    data() {
      return {
        songReady: false,
        currentTime: 0, //当前时间
        radius: 32,
        currentLyric: null,
        currentLineNum: 0,
        swiperOption: {
          pagination: '.swiper-pagination',
          initialSlide: 0,
        },
        playingLyric: '',
        songUrl: ''
      };
    },
    computed: {
      playIcon() {
        return this.playing ? "icon-pause" : "icon-play";
      },
      miniIcon() {
        return this.playing ? "icon-pause-mini" : "icon-play-mini";
      },
      cdcls() {
        return this.playing ? "play" : "play pause";
      },
      disableCls() {
        return this.songReady ? "" : "disable";
      },
      percent() {
        return this.currentTime / this.currentSong.duration
      },
      // songUrl() {
      //   var url
      //   if (!this.currentSong.url && this.currentSong.songmid) {

      //     getSingerUrl(this.currentSong.songmid).then(res => {
      //       // this.currentSong.url = res
      //       url = res
      //       console.log(1,url)
      //     })
      //     setTimeout(()=>{
      //       console.log(2,url,this.currentSong.url)
      //     },500)

      //     return url
      //   }
      //   return this.currentSong.url
      // },
      ...mapGetters([
        "fullScreen",
        "playing",
        "currentIndex"
      ])
    },
    methods: {
      back() {
        this.setFullScreen(false);
      },
      open() {
        this.setFullScreen(true);
      },
      enter(el, done) {
        const {
          x,
          y,
          scale
        } = this._getPosAndScale();

        let animation = {
          0: {
            transform: `translate3d(${x}px,${y}px,0) scale(${scale})`
          },
          60: {
            transform: `translate3d(0,0,0) scale(1.1)`
          },
          100: {
            transform: `translate3d(0,0,0) scale(1)`
          }
        };

        animations.registerAnimation({
          name: "move",
          // 插入自定义的动画
          animation,
          // 参数配置
          presets: {
            duration: 400, // 持续时间
            easing: "linear" // 过度效果
          }
        });

        animations.runAnimation(this.$refs.cdWrapper, "move", done);
      },
      afterEnter() {
        // 取消动画
        animations.unregisterAnimation("move");
        this.$refs.cdWrapper.style.animation = "";
      },
      leave(el, done) {
        this.$refs.cdWrapper.style.transition = "all .4s";
        const {
          x,
          y,
          scale
        } = this._getPosAndScale();
        this.$refs.cdWrapper.style[
          "transform"
        ] = `translate3d(${x}px,${y}px,0) scale(${scale})`;
        this.$refs.cdWrapper.addEventListener("transitionend", done);
      },
      afterLeave() {
        this.$refs.cdWrapper.style.transition = "";
        this.$refs.cdWrapper.style["transform"] = "";
      },
      //播放暂停
      togglePlaying() {
        if (!this.songReady) {
          return;
        }
        this.setPlayingState(!this.playing);
        if (this.currentLyric) {
          this.currentLyric.togglePlay()
        }
      },
      // 歌曲播放结束
      end() {
        if (this.mode === playMode.loop) {
          this.loop()
        } else {
          this.next()
        }
      },
      // 循环单曲
      loop() {
        this.$refs.audio.currentTime = 0
        this.$refs.audio.play()
        if (this.currentLyric) {
          this.currentLyric.seek(0)
        }
      },
      //下一曲
      next() {
        if (!this.songReady) {
          return;
        }
        if (this.playList.length === 1) {
          this.loop()
          return
        } else {
          let index = this.currentIndex + 1;
          if (index === this.playList.length) {
            index = 0;
          }
          this.setCurrentIndex(index);
          if (!this.playing) {
            this.togglePlaying();
          }
        }
        this.songReady = false;
      },
      //上一曲
      prev() {
        if (!this.songReady) {
          return;
        }
        if (this.playList.length === 1) {
          this.loop()
          return
        } else {
          let index = this.currentIndex - 1;
          if (index === -1) {
            index = this.playList.length - 1;
          }
          this.setCurrentIndex(index);
          if (!this.playing) {
            this.togglePlaying();
          }
        }
        this.songReady = false;
      },
      ready() {
        this.songReady = true;
        this.savePlayHistory(this.currentSong)
      },
      error() {
        this.songReady = true;
      },
      //播放器播放时执行事件
      updateTime(e) {
        this.currentTime = e.target.currentTime;
      },
      // 时间转换
      format(intaval) {
        intaval = intaval | 0;
        const minute = (intaval / 60) | 0;
        const second = (intaval % 60) | 0;
        return `${minute}:${this._pad(second)}`;
      },
      // 改变播放器进度
      onProgressBarChange(percent) {
        const currentTime = this.currentSong.duration * percent
        this.$refs.audio.currentTime = currentTime
        if (!this.playing) {
          this.togglePlaying()
        }
        if (this.currentLyric) {
          this.currentLyric.seek(currentTime * 1000)
        }
      },
      // 歌词
      getLyric() {
        this.currentSong.getLyric().then((res) => {
          if (this.currentSong.lyric !== res) {
            return
          }
          this.currentLyric = new Lyric(res, this.handleLyric)
          if (this.playing) {
            this.currentLyric.play()
          }
        }).catch(() => {
          this.currentLyric = null
          this.playingLyric = ''
          this.currentLineNum = 0
        })
      },
      // 歌词回调
      handleLyric({
        lineNum,
        txt
      }) {
        this.currentLineNum = lineNum
        if (lineNum > 5) {
          let lineEl = this.$refs.lyricLine[lineNum - 5]
          this.$refs.lyricList.scrollToElement(lineEl, 1000)
        } else {
          this.$refs.lyricList.scrollTo(0, 0, 1000)
        }
        this.playingLyric = txt
      },
      // 显示播放列表
      iconShowList() {
        this.$refs.playListRef.show()
      },
      // 获取坐标
      _getPosAndScale() {
        const tatgetWidth = 40;
        const paddingLeft = 40;
        const paddingBottom = 30;
        const paddingTop = 80;
        const width = window.innerWidth * 0.8;
        const scale = tatgetWidth / width;
        const x = -(window.innerWidth / 2 - paddingLeft);
        const y = window.innerHeight - paddingTop - width / 2 - paddingBottom;
        return {
          x,
          y,
          scale
        };
      },
      // 补0
      _pad(num, n = 2) {
        let len = num.toString().length;
        while (len < n) {
          num = "0" + num;
          len++;
        }
        return num;
      },
      ...mapMutations({
        setFullScreen: "SET_FULL_SCREEN"
      }),
      ...mapActions(['savePlayHistory'])
    },
    watch: {
      currentSong(newSong, oldSong) {
        if (!newSong.id) {
          return
        }
        if (!this.currentSong.url && this.currentSong.mid) {
          if (newSong.id !== oldSong.id) {
            getSingerUrl(this.currentSong.mid).then(res => {
              this.songUrl = res
            })
          }
        } else {
          this.songUrl = this.currentSong.url
        }
        if (newSong.id === oldSong.id) {
          return
        }
        if (this.currentLyric) {
          this.currentLyric.stop()
        }
        clearTimeout(this.time)
        this.time = setTimeout(() => {
          this.$refs.audio.play();
          this.getLyric()
        }, 1000);
      },
      playing(newPlaying) {
        const audio = this.$refs.audio;
        this.$nextTick(() => {
          newPlaying ? audio.play() : audio.pause();
        });
      }
    },
    components: {
      progressBar,
      progressCircle,
      Scroll,
      PlayList
    }
  };

</script>
